// 游戏核心引擎类
class GameEngine {
    constructor() {
        this.currentScreen = 'main-menu';
        this.previousScreen = null;
        this.selectedCharacter = null;
        this.currentFloor = 1;
        this.maxFloor = 15;
        this.player = null;
        this.currentEnemies = [];
        this.playerHand = [];
        this.playerDeck = [];
        this.playerDiscardPile = [];
        this.playerExhaustPile = [];
        this.playerRelics = [];
        this.playerPotions = [];
        this.playerGold = 0;
        this.gameState = 'menu'; // menu, playing, battle, shop, hanfu, gameOver
        this.battleTurn = 0;
        this.selectedCard = null;
        this.battleLog = [];
        this.lastBattleGoldReward = 0; // 本次战斗获得的金币
        // 回合与联动计数
        this.currentTurnCardCount = 0;
        this.currentTurnAttackCount = 0;
        this.nextSpellDouble = false;
        this.rhythmMasteryActive = false;
        this.rhythmTriggersThisTurn = 0;
        this.pendingDraw = 0;
        
        // 连击系统
        this.comboCount = 0; // 当前连击数
        this.lastAttackTime = 0; // 上次攻击时间
        this.comboTimeout = 2000; // 连击超时时间（毫秒）
        
        // 商店临时数据
        this.shopItems = { cards: [], relics: [], potions: [] };
        
        // 随机种子：用于可复现地图
        this.seed = (Date.now() >>> 0);
        // 地图系统（基于种子）
        this.mapSystem = new MapSystem(this.seed);
        this.mapRenderer = new MapRenderer(this.mapSystem);
        
        // 升级动画锁
        this.upgradeAnimationLock = false;

        // 角色头像帧动画
        this.avatarFrames = {
            'xu': ['image/role/xu_1.jpg', 'image/role/xu_2.jpg', 'image/role/xu_3.jpg', 'image/role/xu_4.jpg'],
            'ling': ['image/role/ling_1.jpg', 'image/role/ling_2.jpg', 'image/role/ling_3.jpg', 'image/role/ling_4.jpg'],
            'che': ['image/role/che_1.jpg', 'image/role/che_2.jpg', 'image/role/che_3.jpg', 'image/role/che_4.jpg']
        };
        this.avatarFallbackMap = {
            'xu': '素材/xu.jpg',
            'ling': '素材/ling.jpg',
            'che': '素材/che.jpg'
        };
        this.avatarAnimations = {};

        // 难度与成长统计
        this.difficultyTier = 1;
        this.maxUnlockedTier = 1;
        this.totalBattleTurns = 0;
        this.elitesDefeated = 0;
        this.bossDefeated = 0;
        this.cardsPurged = 0;

        // 特殊事件与弹窗状态
        this.heavenlyBlessingResolved = false;
        this.wasBossBattle = false;

        // 模块化管理器
        this.battleManager = new BattleManager(this);
        this.eventManager = new EventManager(this);
    }

    // 进入事件界面
    enterEvent() {
        if (this.eventManager) {
            this.eventManager.enterEvent();
        }
    }

    // 渲染随机事件
    renderRandomEvent() {
        if (this.eventManager) {
            this.eventManager.renderRandomEvent();
        }
    }

    updateEventUI() {
        if (this.eventManager) {
            this.eventManager.updateEventUI();
        }
    }

    // 生成随机事件定义
    generateRandomEvent() {
        if (this.eventManager) {
            return this.eventManager.generateRandomEvent();
        }
    }

    // 事件1：路边的幸运转盘
    eventLuckyWheel() {
        if (this.eventManager) {
            return this.eventManager.eventLuckyWheel();
        }
    }

    // 事件2：到图书馆学习
    eventLibraryStudy() {
        if (this.eventManager) {
            return this.eventManager.eventLibraryStudy();
        }
    }

    // 事件3：回老家帮忙
    eventHometownTrip() {
        if (this.eventManager) {
            return this.eventManager.eventHometownTrip();
        }
    }

    // 事件4：公园捡钱
    eventParkTripMessage() {
        if (this.eventManager) {
            return this.eventManager.eventParkTripMessage();
        }
    }

    eventParkTrip() {
        if (this.eventManager) {
            return this.eventManager.eventParkTrip();
        }
    }

    // 事件5：周末逛商场
    eventMallWeekend() {
        if (this.eventManager) {
            return this.eventManager.eventMallWeekend();
        }
    }

    // 工具：从手牌按类型随机升级若干张
    upgradeRandomHandCardsByType(type, count) {
        if (this.eventManager) {
            return this.eventManager.upgradeRandomHandCardsByType(type, count);
        }
    }

    // 工具：从全牌组(抽+弃+手)按类型随机升级若干张
    upgradeRandomFromAllByType(type, count) {
        if (this.eventManager) {
            return this.eventManager.upgradeRandomFromAllByType(type, count);
        }
    }

    // 工具：随机移除若干张牌（优先从弃牌堆和牌库，避免空手）
    removeRandomFromDeck(count) {
        if (this.eventManager) {
            return this.eventManager.removeRandomFromDeck(count);
        }
    }

    // 初始化游戏
    init() {
        this.setupEventListeners();
        this.showScreen('main-menu');
        console.log('Game initialized');
        // 载入历史
        this.loadRunHistory();
        // 载入上次seed并填充输入框
        try {
            const savedSeed = localStorage.getItem('h5_uneven_seed');
            const seedInput = document.getElementById('seed-input');
            if (seedInput && savedSeed) {
                seedInput.value = parseInt(savedSeed, 10) || '';
            }
        } catch(e) {
            console.error('加载seed失败', e);
        }
        this.loadDifficultyState();
        this.updateDifficultyUI();
    }

    // 设置事件监听器
    setupEventListeners() {
        const safeAddListener = (id, event, handler) => {
            const element = document.getElementById(id);
            if (element) {
                element.addEventListener(event, handler);
            }
        };

        // 角色选择
        document.querySelectorAll('.character-card').forEach(card => {
            card.addEventListener('click', (e) => {
                this.selectCharacter(e.currentTarget.dataset.character);
            });
        });

        // 开始游戏
        safeAddListener('start-game', 'click', () => {
            // 读取种子（可选）
            const seedInput = document.getElementById('seed-input');
            if (seedInput && seedInput.value !== '') {
                const n = Number(seedInput.value);
                if (Number.isFinite(n)) {
                    this.seed = (Math.floor(n) >>> 0);
                    try { localStorage.setItem('h5_uneven_seed', String(this.seed)); } catch(e) {}
                }
            } else {
                // 随机生成并保存
                this.seed = (Date.now() >>> 0);
                try { localStorage.setItem('h5_uneven_seed', String(this.seed)); } catch(e) {}
            }
            // 使用新的seed重新初始化MapSystem
            this.mapSystem = new MapSystem(this.seed);
            this.mapRenderer = new MapRenderer(this.mapSystem);
            // 更新复制按钮显示
            this.updateSeedCopyButton();
            this.startGame();
        });

        // 随机seed按钮
        const seedRandBtn = document.getElementById('seed-random');
        if (seedRandBtn) {
            seedRandBtn.addEventListener('click', () => {
                const s = (Math.floor(Math.random() * 0xFFFFFFFF) >>> 0);
                const seedInput = document.getElementById('seed-input');
                if (seedInput) seedInput.value = String(s);
            });
        }

        // 复制seed按钮
        const seedCopyBtn = document.getElementById('seed-copy');
        if (seedCopyBtn) {
            seedCopyBtn.addEventListener('click', () => {
                const seedInput = document.getElementById('seed-input');
                if (seedInput && seedInput.value) {
                    navigator.clipboard.writeText(seedInput.value).then(() => {
                        // 临时显示复制成功提示
                        const originalText = seedCopyBtn.textContent;
                        seedCopyBtn.textContent = '✓';
                        setTimeout(() => {
                            seedCopyBtn.textContent = originalText;
                        }, 1000);
                    }).catch(err => {
                        console.error('复制失败', err);
                    });
                }
            });
        }

        // 战斗相关
        safeAddListener('end-turn-bottom', 'click', () => this.endTurn());

        // 卡牌堆查看相关
        safeAddListener('draw-pile-view', 'click', () => this.showDeckViewTab('draw'));
        safeAddListener('discard-pile-view', 'click', () => this.showDeckViewTab('discard'));
        safeAddListener('exhaust-pile-view', 'click', () => this.showDeckViewTab('exhaust'));

        // 地图页面卡牌包查看
        safeAddListener('map-deck-view', 'click', () => this.showDeckView());

        // 地图页面遗物查看
        const mapRelicsViewBtn = document.getElementById('map-relics-view');
        if (mapRelicsViewBtn) {
            mapRelicsViewBtn.addEventListener('click', () => {
                this.showRelicsView();
            });
        }

        // 战斗页面遗物查看
        const relicsViewBtn = document.getElementById('relics-view');
        if (relicsViewBtn) {
            relicsViewBtn.addEventListener('click', () => {
                this.showRelicsView();
            });
        }

        // 汉府相关
        safeAddListener('rest-heal', 'click', () => this.restAndHeal());
        safeAddListener('upgrade-card', 'click', () => this.showCardUpgrade());
        safeAddListener('remove-card', 'click', () => this.showCardRemoval());
        safeAddListener('leave-hanfu', 'click', () => this.leaveHanfu());

        // 卡牌升级相关
        safeAddListener('cancel-upgrade', 'click', () => this.cancelCardUpgrade());

        // 卡牌包查看相关
        safeAddListener('deck-view', 'click', () => this.showDeckView());

        // 商店相关
        safeAddListener('leave-shop', 'click', () => this.leaveShop());

        // 战斗结果
        const continueBtn = document.getElementById('continue-adventure');
        if (continueBtn) {
            continueBtn.addEventListener('click', () => {
                console.log('继续冒险按钮被点击');
                this.continueAdventure();
            });
        }

        // 游戏结束
        safeAddListener('restart-game', 'click', () => this.restartGame());

        // 历史记录
        const viewLogsBtn = document.getElementById('view-logs');
        if (viewLogsBtn) {
            viewLogsBtn.addEventListener('click', () => {
                this.showLogsScreen();
            });
        }
        const logsBackBtn = document.getElementById('logs-back');
        if (logsBackBtn) {
            logsBackBtn.addEventListener('click', () => {
                this.showScreen('main-menu');
            });
        }
        const logsClearBtn = document.getElementById('logs-clear');
        if (logsClearBtn) {
            logsClearBtn.addEventListener('click', () => {
                this.clearRunHistory();
                this.renderRunHistory();
            });
        }

        const difficultyPrev = document.getElementById('difficulty-prev');
        const difficultyNext = document.getElementById('difficulty-next');
        if (difficultyPrev) {
            difficultyPrev.addEventListener('click', () => {
                this.changeDifficulty(-1);
            });
        }
        if (difficultyNext) {
            difficultyNext.addEventListener('click', () => {
                this.changeDifficulty(1);
            });
        }

        const victoryAdvanceBtn = document.getElementById('victory-advance');
        if (victoryAdvanceBtn) {
            victoryAdvanceBtn.addEventListener('click', () => {
                this.advanceDifficultyAfterVictory();
            });
        }
        const victoryReturnBtn = document.getElementById('victory-return');
        if (victoryReturnBtn) {
            victoryReturnBtn.addEventListener('click', () => {
                this.returnToMainMenu();
            });
        }

        safeAddListener('card-choice-cancel', 'click', () => {
            if (this.eventManager) {
                this.eventManager.closeCardChoiceModal(true);
            }
        });
    }

    // 选择角色
    selectCharacter(characterType) {
        // 移除之前的选择
        document.querySelectorAll('.character-card').forEach(card => {
            card.classList.remove('selected');
        });

        // 选择新角色
        document.querySelector(`[data-character="${characterType}"]`).classList.add('selected');
        this.selectedCharacter = characterType;
        document.getElementById('start-game').disabled = false;
    }

    // 开始游戏
    startGame() {
        if (!this.selectedCharacter) return;

        console.log('Starting game with character:', this.selectedCharacter);
        console.log('Using seed:', this.seed);

        this.clearAvatarAnimations();
        this.avatarAnimations = {};

        // 创建玩家角色
        this.player = new Player(this.selectedCharacter);
        this.playerGold = 0;
        this.currentFloor = 1;
        this.gameState = 'playing';
        this.totalBattleTurns = 0;
        this.elitesDefeated = 0;
        this.bossDefeated = 0;
        this.cardsPurged = 0;
        this.heavenlyBlessingResolved = false;
        this.wasEliteBattle = false;
        this.wasBossBattle = false;

        // 初始化卡组
        this.initializeDeck();
        this.initializeRelics();
        // 起始遗物：入学礼包（加快前期成长，便于通过首个精英）
        const starterRelic = relicDatabase.getRelicByName('入学礼包');
        if (starterRelic) {
            this.playerRelics.push(starterRelic);
        }
        this.initializePotions();

        console.log('Player initialized:', this.player);
        console.log('Deck size:', this.playerDeck.length);

        // 更新角色头像
        this.updatePlayerAvatar();
        this.updateDifficultyUI();

        // 重置地图系统（使用当前seed）
        this.mapSystem.reset();
        this.mapSystem.currentFloor = 1;
        
        // 设置地图渲染器的节点点击回调
        this.mapRenderer.setNodeClickCallback((node) => {
            this.handleNodeClick(node);
        });

        // 更新seed输入框和复制按钮
        const seedInput = document.getElementById('seed-input');
        if (seedInput) {
            seedInput.value = String(this.seed);
        }
        this.updateSeedCopyButton();

        // 显示地图界面
        this.showMap();
        this.updateMapUI();
        this.updateUI();
        setTimeout(() => this.triggerHeavenlyBlessing(), 120);
    }

    // 更新seed复制按钮显示
    updateSeedCopyButton() {
        const seedCopyBtn = document.getElementById('seed-copy');
        const seedInput = document.getElementById('seed-input');
        if (seedCopyBtn && seedInput && seedInput.value) {
            seedCopyBtn.style.display = 'inline-block';
        } else if (seedCopyBtn) {
            seedCopyBtn.style.display = 'none';
        }
    }
    
    // 获取角色头像路径
    getCharacterAvatarFrames(characterType) {
        const fallbackKey = 'xu';
        if (!characterType) {
            const fallback = this.avatarFallbackMap?.[fallbackKey];
            return fallback ? [fallback] : [];
        }
        const frames = this.avatarFrames?.[characterType];
        if (frames && frames.length) {
            return frames;
        }
        const fallback = this.avatarFallbackMap?.[characterType];
        if (fallback) {
            return [fallback];
        }
        return [];
    }
    
    getCharacterAvatarPath(characterType) {
        const frames = this.getCharacterAvatarFrames(characterType);
        return frames[0] || '';
    }
    
    // 更新角色头像显示
    updatePlayerAvatar() {
        if (!this.selectedCharacter) return;
        const frames = this.getCharacterAvatarFrames(this.selectedCharacter);
        this.startAvatarAnimation('player-avatar', frames);
        this.startAvatarAnimation('map-player-avatar', frames);
        this.startAvatarAnimation('battle-player-avatar', frames);
    }

    areAvatarFrameSetsEqual(a = [], b = []) {
        if (a.length !== b.length) return false;
        for (let i = 0; i < a.length; i++) {
            if (a[i] !== b[i]) return false;
        }
        return true;
    }

    startAvatarAnimation(elementId, frames = [], interval = 800) {
        if (!elementId || !frames || frames.length === 0) return;
        const element = document.getElementById(elementId);
        if (!element) return;

        const existing = this.avatarAnimations[elementId];
        if (existing && this.areAvatarFrameSetsEqual(existing.frames, frames)) {
            const currentIndex = existing.index || 0;
            element.src = existing.frames[currentIndex] || existing.frames[0];
            return;
        }

        this.stopAvatarAnimation(elementId);

        const state = {
            frames: [...frames],
            index: 0,
            timer: null
        };
        element.src = state.frames[0];
        if (state.frames.length > 1) {
            state.timer = setInterval(() => {
                state.index = (state.index + 1) % state.frames.length;
                element.src = state.frames[state.index];
            }, interval);
        }
        this.avatarAnimations[elementId] = state;
    }

    stopAvatarAnimation(elementId) {
        const state = this.avatarAnimations[elementId];
        if (!state) return;
        if (state.timer) {
            clearInterval(state.timer);
        }
        delete this.avatarAnimations[elementId];
    }

    clearAvatarAnimations() {
        Object.keys(this.avatarAnimations || {}).forEach(id => this.stopAvatarAnimation(id));
    }

    // 初始化卡组
    initializeDeck() {
        this.playerDeck = [...this.player.startingDeck];
        this.playerDiscardPile = [];
        this.playerExhaustPile = [];
        this.shuffleDeck();
        this.drawHand();
    }

    // 初始化遗物
    initializeRelics() {
        this.playerRelics = [];
    }

    // 初始化药水
    initializePotions() {
        this.playerPotions = [
            { type: 'healing', name: '777感冒灵', effect: 25 }
        ];
    }

    // 洗牌
    shuffleDeck() {
        for (let i = this.playerDeck.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this.playerDeck[i], this.playerDeck[j]] = [this.playerDeck[j], this.playerDeck[i]];
        }
    }

    // 添加卡牌到手牌（如果超过上限，多出的放入弃牌堆）
    addCardToHand(card) {
        if (!card) return;
        
        if (this.playerHand.length < this.player.maxHandSize) {
            // 手牌未满，直接加入
            this.playerHand.push(card);
            return true; // 成功加入手牌
        } else {
            // 手牌已满，放入弃牌堆
            this.playerDiscardPile.push(card);
            return false; // 放入弃牌堆
        }
    }

    // 抽牌（每回合固定抽5张牌）
    drawHand() {
        const targetHandSize = 5; // 目标手牌数量：5张
        const currentHandSize = this.playerHand.length;
        const cardsToDraw = Math.max(0, targetHandSize - currentHandSize); // 计算需要抽多少张才能达到5张
        
        let actualDrawn = 0;
        for (let i = 0; i < cardsToDraw; i++) {
            // 检查手牌上限
            if (this.playerHand.length >= this.player.maxHandSize) {
                break; // 手牌已满，停止抽牌
            }
            
            if (this.playerDeck.length === 0) {
                this.reshuffleDeck();
            }
            
            if (this.playerDeck.length > 0) {
                const card = this.playerDeck.pop();
                this.addCardToHand(card);
                actualDrawn++;
            }
        }
        
        if (actualDrawn > 0) {
            this.addBattleLog(`抽牌: 获得 ${actualDrawn} 张卡牌`);
        }
        this.updateHandDisplay();
    }

    // 重新洗牌
    reshuffleDeck() {
        if (this.playerDiscardPile.length > 0) {
            this.playerDeck = [...this.playerDiscardPile];
            this.playerDiscardPile = [];
            this.shuffleDeck();
            this.addBattleLog('弃牌堆重新洗入抽牌堆');
        }
    }

    // 弃牌
    discardCard(card) {
        const cardIndex = this.playerHand.indexOf(card);
        if (cardIndex > -1) {
            this.playerHand.splice(cardIndex, 1);
            this.playerDiscardPile.push(card);
            this.addBattleLog(`弃牌: ${card.name}`);
        }
    }

    // 消耗卡牌
    exhaustCard(card) {
        const cardIndex = this.playerHand.indexOf(card);
        if (cardIndex > -1) {
            this.playerHand.splice(cardIndex, 1);
            this.playerExhaustPile.push(card);
            this.addBattleLog(`消耗: ${card.name}`);
        }
    }

    // 显示地图
    showMap() {
        this.showScreen('map-screen');
        this.mapRenderer.renderMap('map-container');
        this.updateMapUI();
    }

    // 更新地图UI
    updateMapUI() {
        if (this.player) {
            document.getElementById('map-player-health').textContent = this.player.health;
            document.getElementById('map-player-energy').textContent = this.player.energy;
            document.getElementById('map-player-gold').textContent = this.playerGold;
            document.getElementById('map-current-floor').textContent = this.mapSystem.currentFloor;
            this.updateMapPotionsDisplay();
            this.updateMapRelicsDisplay();
            // 确保头像显示
            this.updatePlayerAvatar();
        }
        const mapDiff = document.getElementById('map-difficulty-label');
        if (mapDiff) {
            mapDiff.textContent = this.getDifficultyLabel(this.difficultyTier);
        }
    }

    // 更新地图药水显示
    updateMapPotionsDisplay() {
        const potionsContainer = document.getElementById('map-potions-display');
        if (!potionsContainer) return;
        
        potionsContainer.innerHTML = '';
        
        if (this.playerPotions.length === 0) {
            potionsContainer.innerHTML = '<span style="color: #999; font-style: italic;">无</span>';
            return;
        }
        
        this.playerPotions.forEach((potion, index) => {
            const potionIcon = document.createElement('span');
            potionIcon.className = 'potion-icon';
            potionIcon.textContent = potion.name;
            potionIcon.title = potion.description || potion.name;
            potionsContainer.appendChild(potionIcon);
        });
    }

    // 更新地图遗物显示
    updateMapRelicsDisplay() {
        const relicsContainer = document.getElementById('map-relics-display');
        if (!relicsContainer) return;
        
        relicsContainer.innerHTML = '';
        
        if (!this.playerRelics || this.playerRelics.length === 0) {
            relicsContainer.innerHTML = '<span style="color: #999; font-style: italic;">无</span>';
            return;
        }
        
        // 只显示前3个，其他用数字表示
        const displayCount = Math.min(3, this.playerRelics.length);
        for (let i = 0; i < displayCount; i++) {
            const relic = this.playerRelics[i];
            const relicIcon = document.createElement('span');
            relicIcon.className = `relic-icon rarity-${relic.rarity || 'common'}`;
            relicIcon.textContent = relic.name;
            relicIcon.title = `${relic.name}: ${relic.description}`;
            relicsContainer.appendChild(relicIcon);
        }
        
        if (this.playerRelics.length > 3) {
            const moreText = document.createElement('span');
            moreText.className = 'relic-more';
            moreText.textContent = `+${this.playerRelics.length - 3}`;
            moreText.title = `还有${this.playerRelics.length - 3}件遗物`;
            relicsContainer.appendChild(moreText);
        }
    }

    // 处理节点点击
    handleNodeClick(node) {
        console.log('Handling node click:', node);
        
        // 选择节点
        const selectedNode = this.mapSystem.selectNode(node.id);
        if (!selectedNode) return;

        console.log('节点已选择，更新地图显示');
        // 更新地图显示以反映节点状态变化
        this.mapRenderer.updateMap();

        // 根据节点类型执行相应操作
        switch (selectedNode.type) {
            case 'battle':
                this.startNormalBattle();
                break;
            case 'elite':
                this.startEliteBattle();
                break;
            case 'boss':
                this.startBossBattle();
                break;
            case 'hanfu':
                this.enterHanfu();
                break;
            case 'shop':
                this.enterShop();
                break;
            case 'event':
                this.enterEvent();
                break;
        }
    }

    // 返回地图
    returnToMap() {
        this.showMap();
        this.mapRenderer.updateMap();
    }

    // 开始普通战斗
    startNormalBattle() {
        if (this.battleManager) {
            this.battleManager.startNormalBattle();
        }
    }

    // 开始精英战斗
    startEliteBattle() {
        if (this.battleManager) {
            this.battleManager.startEliteBattle();
        }
    }

    // 开始Boss战斗
    startBossBattle() {
        if (this.battleManager) {
            this.battleManager.startBossBattle();
        }
    }
    
    // 播放战斗背景音乐
    playBattleMusic() {
        if (this.battleManager) {
            this.battleManager.playBattleMusic();
        }
    }
    
    // 停止战斗背景音乐
    stopBattleMusic() {
        if (this.battleManager) {
            this.battleManager.stopBattleMusic();
        }
    }

    // 生成敌人
    generateEnemies() {
        if (this.battleManager) {
            return this.battleManager.generateEnemies();
        }
    }

    // 生成精英敌人
    generateEliteEnemies() {
        if (this.battleManager) {
            return this.battleManager.generateEliteEnemies();
        }
    }

    // 生成Boss敌人
    generateBossEnemies() {
        if (this.battleManager) {
            return this.battleManager.generateBossEnemies();
        }
    }

    // 获取精英类型
    getEliteTypesForFloor(floor) {
        if (this.battleManager) {
            return this.battleManager.getEliteTypesForFloor(floor);
        }
        return [];
    }

    // 检查是否是精英楼层
    isEliteFloor(floor) {
        if (this.battleManager) {
            return this.battleManager.isEliteFloor(floor);
        }
        return false;
    }

    // 检查是否是Boss楼层
    isBossFloor(floor) {
        if (this.battleManager) {
            return this.battleManager.isBossFloor(floor);
        }
        return false;
    }

    // 使用卡牌
    useCard(card) {
        if (this.battleManager) {
            return this.battleManager.useCard(card);
        }
    }

    // 执行卡牌效果
    executeCardEffect(card) {
        if (this.battleManager) {
            return this.battleManager.executeCardEffect(card);
        }
    }

    // 执行法术攻击的特殊效果
    executeSpellAttack(card) {
        if (this.battleManager) {
            return this.battleManager.executeSpellAttack(card);
        }
    }

    // 执行技能效果
    executeSkill(card) {
        if (this.battleManager) {
            return this.battleManager.executeSkill(card);
        }
    }

    // 造成伤害
    dealDamage(damage) {
        if (this.battleManager) {
            return this.battleManager.dealDamage(damage);
        }
    }
    
    // 延迟抽牌队列
    queueDraw(n = 1) {
        if (this.battleManager) {
            return this.battleManager.queueDraw(n);
        }
    }

    // 抽指定数量的牌（尊重手牌上限）
    drawCards(n = 1) {
        if (this.battleManager) {
            return this.battleManager.drawCards(n);
        }
    }

    // 对所有敌人造成伤害
    dealDamageToAll(damage) {
        if (this.battleManager) {
            return this.battleManager.dealDamageToAll(damage);
        }
    }
    
    // 播放音效
    playSound(soundName) {
        if (this.battleManager) {
            return this.battleManager.playSound(soundName);
        }
    }
    
    // 更新连击计数
    updateCombo() {
        if (this.battleManager) {
            return this.battleManager.updateCombo();
        }
    }
    
    // 显示连击文字
    showComboText() {
        if (this.battleManager) {
            return this.battleManager.showComboText();
        }
    }
    
    // 显示伤害数字
    showDamageNumber(damage, enemy, isCrit = false) {
        if (this.battleManager) {
            return this.battleManager.showDamageNumber(damage, enemy, isCrit);
        }
    }
    
    // 创建粒子特效
    createHitParticles(enemy, isCrit = false) {
        if (this.battleManager) {
            return this.battleManager.createHitParticles(enemy, isCrit);
        }
    }
    
    // 敌人受击抖动
    shakeEnemy(enemy) {
        if (this.battleManager) {
            return this.battleManager.shakeEnemy(enemy);
        }
    }
    
    // 屏幕震动
    screenShake(damage) {
        if (this.battleManager) {
            return this.battleManager.screenShake(damage);
        }
    }

    // 击败敌人
    defeatEnemy(enemy) {
        if (this.battleManager) {
            return this.battleManager.defeatEnemy(enemy);
        }
    }

    // 战斗胜利
    battleVictory() {
        if (this.battleManager) {
            return this.battleManager.battleVictory();
        }
    }
    
    // 整理牌堆（战斗结束后）
    organizeDeck() {
        if (this.battleManager) {
            return this.battleManager.organizeDeck();
        }
    }
    
    // 绑定继续冒险按钮
    bindContinueButton() {
        if (this.battleManager) {
            return this.battleManager.bindContinueButton();
        }
    }

    // 显示奖励
    displayRewards() {
        if (this.battleManager) {
            return this.battleManager.displayRewards();
        }
    }
    
    // 领取金币奖励（带动画效果）
    claimGoldReward(element, amount) {
        if (this.battleManager) {
            return this.battleManager.claimGoldReward(element, amount);
        }
    }
    
    // 领取遗物奖励（带动画效果，三选一）
    claimRelicReward(relic, element) {
        if (this.battleManager) {
            return this.battleManager.claimRelicReward(relic, element);
        }
    }
    
    // 领取药水奖励（带动画效果）
    claimPotionReward(element, potion) {
        if (this.battleManager) {
            return this.battleManager.claimPotionReward(element, potion);
        }
    }

    // 生成三选一卡牌奖励（按稀有度概率：50%普通，35%罕见，15%稀有；来源：角色池+通用池）
    generateCardRewards() {
        if (this.battleManager) {
            return this.battleManager.generateCardRewards();
        }
    }

    // 领取卡牌奖励（加入卡牌包）
    claimCardReward(card, element) {
        if (this.battleManager) {
            return this.battleManager.claimCardReward(card, element);
        }
    }

    // 跳过卡牌奖励
    skipCardReward() {
        if (this.battleManager) {
            return this.battleManager.skipCardReward();
        }
    }

    // 随机药水
    getRandomPotion() {
        if (this.battleManager) {
            return this.battleManager.getRandomPotion();
        }
    }

    // 结束回合
    endTurn() {
        if (this.battleManager) {
            return this.battleManager.endTurn();
        }
    }

    // 敌人回合
    enemyTurn() {
        if (this.battleManager) {
            return this.battleManager.enemyTurn();
        }
    }

    // 显示敌人台词
    showEnemyDialog() {
        if (this.battleManager) {
            return this.battleManager.showEnemyDialog();
        }
    }

    // 获取敌人台词
    getEnemyDialog(type, isElite, isBoss) {
        if (this.battleManager) {
            return this.battleManager.getEnemyDialog(type, isElite, isBoss);
        }
    }

    // 显示玩家受伤动画和音效
    showPlayerHurt(damage) {
        if (this.battleManager) {
            return this.battleManager.showPlayerHurt(damage);
        }
    }

    // 卡牌使用动画
    animateCardUse(cardElement) {
        if (this.battleManager) {
            return this.battleManager.animateCardUse(cardElement);
        }
    }

    // 显示能量不足警告
    showEnergyInsufficientWarning(card) {
        if (this.battleManager) {
            return this.battleManager.showEnergyInsufficientWarning(card);
        }
    }

    // 更新玩家状态显示
    updatePlayerStatusDisplay() {
        if (this.battleManager) {
            return this.battleManager.updatePlayerStatusDisplay();
        }
    }

    // 渲染状态显示
    renderStatusDisplay(statuses) {
        if (this.battleManager) {
            return this.battleManager.renderStatusDisplay(statuses);
        }
        return '';
    }

    // 显示药水选择
    showPotionSelection() {
        if (this.battleManager) {
            return this.battleManager.showPotionSelection();
        }
    }

    // 使用药水
    usePotion(index) {
        if (this.battleManager) {
            return this.battleManager.usePotion(index);
        }
    }

    // 执行药水效果
    executePotionEffect(potion) {
        if (this.battleManager) {
            return this.battleManager.executePotionEffect(potion);
        }
    }

    // 关闭药水菜单
    closePotionMenu() {
        if (this.battleManager) {
            return this.battleManager.closePotionMenu();
        }
    }

    // 显示卡牌升级
    showCardUpgrade() {
        if (this.hanfuChoiceMade) return;

        this.hanfuActionMode = 'upgrade';
        this.showScreen('card-upgrade-screen');
        this.renderUpgradeCards();
        const title = document.querySelector('#card-upgrade-screen h2');
        if (title) title.textContent = `选择要升级的卡牌（还需 ${Math.max(0, 2 - (this.hanfuUpgradeCount || 0))}/2）`;
    }

    // 渲染可升级的卡牌
    renderUpgradeCards() {
        const container = document.getElementById('upgrade-cards-container');
        const goldDisplay = document.getElementById('upgrade-gold');
        
        goldDisplay.textContent = this.playerGold;

        // 获取所有卡牌（抽牌堆 + 弃牌堆 + 手牌），并标记来源
        const allCardsWithSource = [];
        this.playerDeck.forEach((card, index) => {
            if (!card.upgraded) {
                allCardsWithSource.push({ card, source: 'deck', index });
            }
        });
        this.playerDiscardPile.forEach((card, index) => {
            if (!card.upgraded) {
                allCardsWithSource.push({ card, source: 'discard', index });
            }
        });
        this.playerHand.forEach((card, index) => {
            if (!card.upgraded) {
                allCardsWithSource.push({ card, source: 'hand', index });
            }
        });

        container.innerHTML = '';

        if (allCardsWithSource.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #ccc;">没有可升级的卡牌</p>';
            return;
        }

        // 显示所有可升级的卡牌，包括同名卡牌
        allCardsWithSource.forEach(({ card, source, index }) => {
            const cardElement = this.createUpgradeCardElement(card, source, index);
            container.appendChild(cardElement);
        });
    }

    // 创建升级卡牌元素
    createUpgradeCardElement(card, source, index) {
        const cardElement = document.createElement('div');
        cardElement.className = 'upgrade-card';
        
        // 添加稀有度边框类
        const rarity = card.rarity || 'common';
        cardElement.classList.add(`rarity-${rarity}`);
        
        if (card.upgraded) {
            cardElement.classList.add('upgraded');
        }

        // 存储卡牌的引用信息，用于精确升级
        cardElement.dataset.source = source;
        cardElement.dataset.index = index;

        const upgradedCard = this.getUpgradedCard(card);
        
        // 显示升级状态
        const upgradeStatus = card.upgraded ? ' (已升级)' : '';
        const sourceLabel = source === 'deck' ? '[抽牌堆]' : source === 'discard' ? '[弃牌堆]' : '[手牌]';
        
        cardElement.innerHTML = `
            <div class="upgrade-card-name">${card.name}${upgradeStatus}</div>
            <div class="upgrade-card-source">${sourceLabel}</div>
            ${this.renderUpgradeDifferences(card, upgradedCard)}
            <div class="upgrade-card-tip">点击升级</div>
        `;

        cardElement.addEventListener('click', () => {
            if (card.upgraded || this.upgradeAnimationLock) return;
            this.upgradeAnimationLock = true;
            cardElement.classList.add('card-upgrading');
            setTimeout(() => {
                this.selectCardForUpgrade(card, source, index);
            }, 320);
        });

        return cardElement;
    }

    // 渲染卡牌升级差异
    renderUpgradeDifferences(originalCard, upgradedCard) {
        const diffs = this.getUpgradeDifferences(originalCard, upgradedCard);
        if (!diffs.length) {
            return `
                <div class="upgrade-card-diffs">
                    <div class="stat-change">
                        <span class="stat-label">变化</span>
                        <span class="stat-value">无</span>
                    </div>
                </div>
            `;
        }

        const rows = diffs.map(diff => {
            if (diff.key === 'description') {
                return `
                    <div class="stat-change stat-description">
                        <span class="stat-label">${diff.label}</span>
                        <div class="stat-description-content">
                            <span class="description-before">${this.escapeHtml(diff.before || '—')}</span>
                            <span class="stat-arrow">→</span>
                            <span class="description-after">${this.escapeHtml(diff.after || '—')}</span>
                        </div>
                    </div>
                `;
            }

            const beforeValue = this.escapeHtml(this.formatStatValue(diff.before));
            const afterValue = this.escapeHtml(this.formatStatValue(diff.after));
            const statClass = this.getUpgradeStatClass(diff.key, diff.before, diff.after);
            const badge = diff.badge ? `<span class="stat-badge ${statClass}">${this.escapeHtml(diff.badge)}</span>` : '';

            return `
                <div class="stat-change">
                    <span class="stat-label">${diff.label}</span>
                    <span class="stat-value stat-before">${beforeValue}</span>
                    <span class="stat-arrow">→</span>
                    <span class="stat-value stat-after ${statClass}">${afterValue}</span>
                    ${badge}
                </div>
            `;
        }).join('');

        return `<div class="upgrade-card-diffs">${rows}</div>`;
    }

    getUpgradeDifferences(originalCard, upgradedCard) {
        const diffs = [];
        const addDiff = (key, label, before, after) => {
            if (before === undefined && after === undefined) return;
            if (before === after) return;
            diffs.push({ key, label, before, after });
        };

        const costBefore = originalCard.cost ?? 0;
        const costAfter = upgradedCard.cost ?? costBefore;
        addDiff('cost', '消耗', costBefore, costAfter);

        if (originalCard.type === 'attack') {
            const beforeDamage = this.pickFirstDefined(originalCard, ['damage', 'value']);
            const afterDamage = this.pickFirstDefined(upgradedCard, ['damage', 'value']);
            if (beforeDamage !== afterDamage) {
                diffs.push({ key: 'damage', label: '基础伤害', before: beforeDamage, after: afterDamage });
            }
        } else if (originalCard.type === 'defend') {
            const beforeBlock = this.pickFirstDefined(originalCard, ['block', 'value']);
            const afterBlock = this.pickFirstDefined(upgradedCard, ['block', 'value']);
            if (beforeBlock !== afterBlock) {
                diffs.push({ key: 'block', label: '基础护甲', before: beforeBlock, after: afterBlock });
            }
        } else {
            const beforeValue = this.pickFirstDefined(originalCard, ['value']);
            const afterValue = this.pickFirstDefined(upgradedCard, ['value']);
            if (beforeValue !== afterValue) {
                diffs.push({ key: 'value', label: '基础数值', before: beforeValue, after: afterValue });
            }
        }

        const attributes = [
            { key: 'strength', label: '力量' },
            { key: 'dexterity', label: '敏捷' },
            { key: 'intelligence', label: '智力' },
            { key: 'heal', label: '治疗量' },
            { key: 'poison', label: '毒素层数' },
            { key: 'weakness', label: '虚弱层数' },
            { key: 'draw', label: '抽牌数' },
            { key: 'energy', label: '能量' }
        ];

        attributes.forEach(attr => {
            const before = originalCard[attr.key];
            const after = upgradedCard[attr.key];
            if (before === undefined && after === undefined) return;
            if (before === after) return;
            diffs.push({ key: attr.key, label: attr.label, before, after });
        });

        if ((originalCard.description || '').trim() !== (upgradedCard.description || '').trim()) {
            diffs.push({
                key: 'description',
                label: '效果描述',
                before: originalCard.description || '',
                after: upgradedCard.description || ''
            });
        }

        if (costBefore !== costAfter) {
            const delta = costAfter - costBefore;
            const costDiff = diffs.find(d => d.key === 'cost');
            if (costDiff) {
                costDiff.badge = delta > 0 ? `+${delta}` : `${delta}`;
            }
        }

        return diffs;
    }

    getUpgradeStatClass(key, before, after) {
        if (before === after) return '';
        if (key === 'cost') {
            return after < before ? 'stat-good' : 'stat-bad';
        }
        const higherIsBetter = ['damage', 'value', 'block', 'strength', 'dexterity', 'intelligence', 'heal', 'draw', 'energy', 'poison', 'weakness'];
        if (higherIsBetter.includes(key)) {
            if (after === undefined) return 'stat-bad';
            if (before === undefined) return 'stat-good';
            return after > before ? 'stat-good' : 'stat-bad';
        }
        return after > before ? 'stat-good' : 'stat-bad';
    }

    pickFirstDefined(card, keys) {
        for (const key of keys) {
            if (card && card[key] !== undefined) {
                return card[key];
            }
        }
        return undefined;
    }

    formatStatValue(value) {
        if (value === null || value === undefined || Number.isNaN(value)) return '—';
        return typeof value === 'number' ? value.toString() : value;
    }

    escapeHtml(text) {
        if (text === null || text === undefined) return '';
        return String(text)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/\n/g, '<br>');
    }

    // 选择卡牌进行升级
    selectCardForUpgrade(card, source, index) {
        // 播放卡牌升级音效
        this.playSound('upgrade');
        
        // 只升级选中的这一张卡牌
        this.upgradeSingleCard(card, source, index);
        this.addBattleLog(`升级卡牌: ${card.name} (免费)`);
        this.hanfuUpgradeCount = (this.hanfuUpgradeCount || 0) + 1;
        if (this.hanfuUpgradeCount < 2) {
            // 继续选择第二张，刷新列表与标题，保持在升级界面
            this.upgradeAnimationLock = false;
            this.renderUpgradeCards();
            const title = document.querySelector('#card-upgrade-screen h2');
            if (title) title.textContent = `选择要升级的卡牌（还需 ${2 - this.hanfuUpgradeCount}/2）`;
            return;
        }
        // 完成两张升级，结束本次汉府
        this.hanfuChoiceMade = true;
        this.disableHanfuOptions();
        this.upgradeAnimationLock = false;
        this.showScreen('hanfu-screen');
        this.updateHanfuUI();
    }

    // 升级单张卡牌（不升级同名卡牌）
    upgradeSingleCard(card, source, index) {
        // 根据来源找到对应的卡牌数组
        let cardArray;
        switch (source) {
            case 'deck':
                cardArray = this.playerDeck;
                break;
            case 'discard':
                cardArray = this.playerDiscardPile;
                break;
            case 'hand':
                cardArray = this.playerHand;
                break;
            default:
                return;
        }

        // 检查索引是否有效
        if (index < 0 || index >= cardArray.length) {
            return;
        }

        // 获取要升级的具体卡牌对象
        const cardToUpgrade = cardArray[index];
        
        // 检查是否已经升级
        if (cardToUpgrade.upgraded) {
            return;
        }

        // 应用升级效果
        const upgradedCard = this.getUpgradedCard(cardToUpgrade);
        
        // 将升级后的属性应用到这张卡牌
        Object.assign(cardToUpgrade, upgradedCard);
        cardToUpgrade.upgraded = true;
    }

    // 升级卡牌（旧方法，保留用于其他地方可能需要升级所有同名卡牌的情况）
    upgradeCard(card) {
        const upgradedCard = this.getUpgradedCard(card);
        upgradedCard.upgraded = true;

        // 更新所有同名卡牌
        this.updateAllCardsWithName(card.name, upgradedCard);
    }

    // 获取升级后的卡牌
    getUpgradedCard(card) {
        const upgradedCard = { ...card };
        
        switch (card.name) {
            case '攻击':
                upgradedCard.damage = card.damage + 3;
                upgradedCard.description = `造成${upgradedCard.damage}点伤害`;
                break;
            case '防御':
                upgradedCard.block = card.block + 3;
                upgradedCard.description = `获得${upgradedCard.block}点护甲`;
                break;
            case '愤怒':
                upgradedCard.strength = (card.strength || 2) + 1;
                upgradedCard.description = `获得${upgradedCard.strength}点力量`;
                break;
            case '坚韧':
                upgradedCard.block = card.block + 2;
                upgradedCard.strength = (card.strength || 1) + 1;
                upgradedCard.description = `获得${upgradedCard.block}点护甲和${upgradedCard.strength}点力量`;
                break;
            case '终结':
                upgradedCard.damage = card.damage + 5;
                upgradedCard.description = `造成${upgradedCard.damage}点伤害，消耗`;
                break;
            case '疾风':
                upgradedCard.damage = card.damage + 2;
                upgradedCard.description = `造成${upgradedCard.damage}点伤害，抽1张牌`;
                break;
            case '冥想':
                upgradedCard.block = card.block + 2;
                upgradedCard.description = `获得${upgradedCard.block}点护甲，抽1张牌`;
                break;
            case '成长':
                // 升级后：各属性从+1变为+2（原效果是各+1，升级后各+2）
                // 注意：这里只是更新描述，实际效果在executeSkill中根据card.upgraded判断
                upgradedCard.description = `获得2点力量、2点敏捷和2点智力`;
                break;
            case '毒素':
                upgradedCard.poison = (card.poison || 2) + 1;
                upgradedCard.description = `施加${upgradedCard.poison}层毒素`;
                break;
            case '虚弱':
                upgradedCard.weakness = (card.weakness || 2) + 1;
                upgradedCard.description = `施加${upgradedCard.weakness}层虚弱`;
                break;
            case '护盾':
                upgradedCard.block = card.block + 3;
                upgradedCard.description = `获得${upgradedCard.block}点护甲，每回合+1护甲`;
                break;
            case '爆发':
                upgradedCard.damage = card.damage + 4;
                upgradedCard.description = `造成${upgradedCard.damage}点伤害，获得2点力量`;
                break;
            case '治疗':
                upgradedCard.heal = (card.heal || 8) + 3;
                upgradedCard.description = `恢复${upgradedCard.heal}点生命值`;
                break;
            case '强化':
                upgradedCard.strength = (card.strength || 1) + 1;
                upgradedCard.description = `获得${upgradedCard.strength}点力量，抽1张牌`;
                break;
            default:
                // 默认升级：减少1点消耗
                if (upgradedCard.cost > 0) {
                    upgradedCard.cost = Math.max(0, upgradedCard.cost - 1);
                }
                break;
        }

        return upgradedCard;
    }

    // 更新所有同名卡牌
    updateAllCardsWithName(cardName, upgradedCard) {
        // 更新抽牌堆
        this.playerDeck.forEach(card => {
            if (card.name === cardName) {
                Object.assign(card, upgradedCard);
            }
        });

        // 更新弃牌堆
        this.playerDiscardPile.forEach(card => {
            if (card.name === cardName) {
                Object.assign(card, upgradedCard);
            }
        });

        // 更新手牌
        this.playerHand.forEach(card => {
            if (card.name === cardName) {
                Object.assign(card, upgradedCard);
            }
        });
    }

    // 取消卡牌升级
    cancelCardUpgrade() {
        this.showScreen('hanfu-screen');
    }

    // 显示卡牌包查看
    showDeckView() {
        // 记录上一个屏幕，用于关闭时返回
        this.previousScreen = this.currentScreen;
        this.showScreen('deck-view-screen');
        this.updateDeckCounts();
        // 显示所有卡牌（合并后的卡牌包）
        this.showAllDeckCards();
    }
    
    // 显示所有卡牌（合并后的卡牌包）
    showAllDeckCards() {
        const container = document.getElementById('deck-cards-container');
        if (!container) return;
        
        container.innerHTML = '';
        
        // 合并所有卡牌：抽牌堆 + 弃牌堆（消耗堆不显示）
        const allCards = [...this.playerDeck, ...this.playerDiscardPile];
        
        if (allCards.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #ccc;">卡牌包为空</p>';
            return;
        }
        
        // 显示所有卡牌
        allCards.forEach(card => {
            const cardElement = this.createDeckCardElement(card);
            container.appendChild(cardElement);
        });
    }

    // 显示特定卡牌堆（从按钮直接调用）- 现在统一显示所有卡牌
    showDeckViewTab(tab) {
        // 记录上一个屏幕，用于关闭时返回
        this.previousScreen = this.currentScreen;
        this.showScreen('deck-view-screen');
        this.updateDeckCounts();
        // 统一显示所有卡牌，不再区分标签页
        this.showAllDeckCards();
    }

    // 直接显示卡牌堆标签页
    showDeckTabDirect(tab) {
        // 更新标签按钮状态
        const tabs = ['draw', 'discard', 'exhaust'];
        const tabLabels = ['抽牌堆', '弃牌堆', '消耗牌堆'];
        const tabIndex = tabs.indexOf(tab);
        
        document.querySelectorAll('.tab-btn').forEach((btn, index) => {
            btn.classList.remove('active');
            if (index === tabIndex) {
                btn.classList.add('active');
            }
        });

        // 显示对应卡牌堆
        const container = document.getElementById('deck-cards-container');
        container.innerHTML = '';

        let cards = [];
        switch (tab) {
            case 'draw':
                cards = this.playerDeck;
                break;
            case 'discard':
                cards = this.playerDiscardPile;
                break;
            case 'exhaust':
                cards = this.playerExhaustPile;
                break;
        }

        if (cards.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #ccc;">该卡牌堆为空</p>';
            return;
        }

        // 平铺显示所有卡牌
        cards.forEach(card => {
            const cardElement = this.createDeckCardElement(card);
            container.appendChild(cardElement);
        });
    }

    // 更新卡牌包计数
    updateDeckCounts() {
        // 计算总卡牌数（抽牌堆 + 弃牌堆，不包含消耗堆）
        const totalCount = this.playerDeck.length + this.playerDiscardPile.length;
        const totalCountElement = document.getElementById('total-deck-count');
        if (totalCountElement) {
            totalCountElement.textContent = totalCount;
        }
        
        // 保留旧的计数元素更新（以防其他地方还在使用）
        const deckCountElement = document.getElementById('deck-count');
        if (deckCountElement) {
            deckCountElement.textContent = this.playerDeck.length;
        }
        const discardCountElement = document.getElementById('discard-count');
        if (discardCountElement) {
            discardCountElement.textContent = this.playerDiscardPile.length;
        }
        const exhaustCountElement = document.getElementById('exhaust-count');
        if (exhaustCountElement) {
            exhaustCountElement.textContent = this.playerExhaustPile.length;
        }
    }

    // 显示卡牌包标签页
    showDeckTab(tab) {
        // 更新标签按钮状态
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');

        // 显示对应卡牌堆
        const container = document.getElementById('deck-cards-container');
        container.innerHTML = '';

        let cards = [];
        switch (tab) {
            case 'draw':
                cards = this.playerDeck;
                break;
            case 'discard':
                cards = this.playerDiscardPile;
                break;
            case 'exhaust':
                cards = this.playerExhaustPile;
                break;
        }

        if (cards.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #ccc;">该卡牌堆为空</p>';
            return;
        }

        // 平铺显示所有卡牌
        cards.forEach(card => {
            const cardElement = this.createDeckCardElement(card);
            container.appendChild(cardElement);
        });
    }

    // 按名称分组卡牌
    groupCardsByName(cards) {
        const groups = new Map();
        cards.forEach(card => {
            const key = card.name;
            if (!groups.has(key)) {
                groups.set(key, { ...card, count: 0 });
            }
            groups.get(key).count++;
        });
        return Array.from(groups.values());
    }

    // 创建卡牌包卡牌元素
    createDeckCardElement(card) {
        const cardElement = document.createElement('div');
        cardElement.className = 'deck-card';
        
        // 添加稀有度与类型样式
        const rarity = card.rarity || 'common';
        cardElement.classList.add(`rarity-${rarity}`);
        const role = this.getCardRole(card);
        cardElement.classList.add(`card-role-${role}`);
        
        if (card.upgraded) {
            cardElement.classList.add('deck-card-upgraded');
        }

        cardElement.innerHTML = this.renderCardContent(card, { mode: 'deck', showUpgrade: false });

        return cardElement;
    }

    // 关闭卡牌包查看
    closeDeckView() {
        // 返回到上一个屏幕
        if (this.previousScreen) {
            this.showScreen(this.previousScreen);
        } else {
            // 如果没有记录上一个屏幕，默认返回游戏界面
            this.showScreen('game-screen');
        }
    }

    // 显示遗物查看界面
    showRelicsView() {
        // 记录上一个屏幕，用于关闭时返回
        this.previousScreen = this.currentScreen;
        this.showScreen('relics-view-screen');
        this.renderAllRelics();
    }

    // 渲染所有遗物
    renderAllRelics() {
        const container = document.getElementById('relics-view-container');
        if (!container) return;

        container.innerHTML = '';

        if (!this.playerRelics || this.playerRelics.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #999;">暂无遗物</p>';
            return;
        }

        this.playerRelics.forEach((relic, index) => {
            const relicElement = this.createRelicElement(relic, index);
            container.appendChild(relicElement);
        });
    }

    // 创建遗物元素
    createRelicElement(relic, index) {
        const relicElement = document.createElement('div');
        relicElement.className = 'relic-item';
        
        // 添加稀有度边框类
        const rarity = relic.rarity || 'common';
        relicElement.classList.add(`rarity-${rarity}`);
        
        // 根据遗物类型添加图标
        const typeIcon = relic.effect.type === 'passive' ? '🔮' : 
                        relic.effect.type === 'active' ? '⚡' : '🎯';
        
        relicElement.innerHTML = `
            <div class="relic-name">${typeIcon} ${relic.name}</div>
            <div class="relic-description">${relic.description}</div>
            <div class="relic-rarity">${this.getRarityText(rarity)}</div>
        `;

        return relicElement;
    }

    // 获取稀有度文本
    getRarityText(rarity) {
        const rarityMap = {
            'common': '普通',
            'uncommon': '罕见',
            'rare': '稀有'
        };
        return rarityMap[rarity] || '未知';
    }

    // 关闭遗物查看界面
    closeRelicsView() {
        // 返回到上一个屏幕
        if (this.previousScreen) {
            this.showScreen(this.previousScreen);
        } else {
            // 如果没有记录上一个屏幕，默认返回游戏界面
            this.showScreen('game-screen');
        }
    }

    // 显示卡牌移除
    showCardRemoval() {
        if (this.hanfuChoiceMade) return;
        // 复用升级界面用于移除
        this.hanfuActionMode = 'remove';
        const container = document.getElementById('upgrade-cards-container');
        const goldDisplay = document.getElementById('upgrade-gold');
        const title = document.querySelector('#card-upgrade-screen h2');
        if (title) title.textContent = `选择要移除的卡牌（还需 ${Math.max(0, 2 - (this.hanfuRemoveCount || 0))}/2）`;
        if (goldDisplay) goldDisplay.textContent = this.playerGold;
        this.showScreen('card-upgrade-screen');
        
        // 获取所有可移除卡牌（抽牌堆 + 弃牌堆），并标记来源
        const allCardsWithSource = [];
        this.playerDeck.forEach((card, index) => {
            allCardsWithSource.push({ card, source: 'deck', index });
        });
        this.playerDiscardPile.forEach((card, index) => {
            allCardsWithSource.push({ card, source: 'discard', index });
        });
        
        container.innerHTML = '';
        if (allCardsWithSource.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #666;">没有可移除的卡牌</p>';
            return;
        }
        
        // 显示所有卡牌，包括同名卡牌
        allCardsWithSource.forEach(({ card, source, index }) => {
            const cardElement = this.createRemovalCardElement(card, source, index);
            container.appendChild(cardElement);
        });
    }
    
    // 创建移除卡牌元素
    createRemovalCardElement(card, source, index) {
            const cardElement = document.createElement('div');
            cardElement.className = 'upgrade-card';
        
        // 添加稀有度边框类
        const rarity = card.rarity || 'common';
        cardElement.classList.add(`rarity-${rarity}`);
        
        if (card.upgraded) {
            cardElement.classList.add('upgraded');
        }
        
        // 存储卡牌的引用信息，用于精确移除
        cardElement.dataset.source = source;
        cardElement.dataset.index = index;
        
        const sourceLabel = source === 'deck' ? '[抽牌堆]' : source === 'discard' ? '[弃牌堆]' : '[手牌]';
        const upgradeLabel = card.upgraded ? ' (已升级)' : '';
        
            cardElement.innerHTML = `
            <div class="upgrade-card-name">${card.name}${upgradeLabel}</div>
            <div class="upgrade-card-source">${sourceLabel}</div>
            <div class="upgrade-card-cost">消耗: ${card.cost}</div>
                <div class="upgrade-card-description">${card.description || ''}</div>
            <div style="color:#ffd700; margin-top: 10px;">点击移除 (免费)</div>
            `;
        
            cardElement.addEventListener('click', () => {
            this.removeSingleCard(source, index);
                this.addBattleLog(`移除卡牌: ${card.name} (免费)`);
            this.hanfuRemoveCount = (this.hanfuRemoveCount || 0) + 1;
            if (this.hanfuRemoveCount < 2) {
                // 继续选择第二张，刷新列表与标题，保持在当前界面
                const title = document.querySelector('#card-upgrade-screen h2');
                if (title) title.textContent = `选择要移除的卡牌（还需 ${2 - this.hanfuRemoveCount}/2）`;
                // 重新渲染待移除卡牌
                this.showCardRemoval();
                return;
            }
            // 完成两张移除，结束本次汉府
                this.hanfuChoiceMade = true;
                this.disableHanfuOptions();
                this.showScreen('hanfu-screen');
            this.updateHanfuUI();
        });
        
        return cardElement;
    }

    // 移除单张卡牌（通过来源和索引精确定位）
    removeSingleCard(source, index) {
        // 根据来源找到对应的卡牌数组
        let cardArray;
        switch (source) {
            case 'deck':
                cardArray = this.playerDeck;
                break;
            case 'discard':
                cardArray = this.playerDiscardPile;
                break;
            case 'hand':
                cardArray = this.playerHand;
                break;
            default:
                return;
        }

        // 检查索引是否有效
        if (index < 0 || index >= cardArray.length) {
            return;
        }

        // 移除卡牌
        const removedCard = cardArray.splice(index, 1)[0];
        this.cardsPurged = (this.cardsPurged || 0) + 1;
        
        // 如果是手牌，更新显示
        if (source === 'hand') {
            this.updateHandDisplay();
        }
        
        return removedCard;
    }

    // 从牌堆/弃牌/手牌移除一张同名卡（旧方法，保留用于兼容）
    removeOneCardByName(cardName) {
        const removeFrom = (arr) => {
            const idx = arr.findIndex(c => c.name === cardName);
            if (idx !== -1) {
                arr.splice(idx, 1);
                return true;
            }
            return false;
        };
        if (removeFrom(this.playerDeck)) return;
        if (removeFrom(this.playerDiscardPile)) return;
        if (removeFrom(this.playerHand)) {
            this.updateHandDisplay();
        }
    }

    // 启用/禁用汉府选项
    enableHanfuOptions() {
        ['rest-heal','upgrade-card','remove-card'].forEach(id => {
            const btn = document.getElementById(id);
            if (btn) btn.disabled = false;
        });
    }
    disableHanfuOptions() {
        ['rest-heal','upgrade-card','remove-card'].forEach(id => {
            const btn = document.getElementById(id);
            if (btn) btn.disabled = true;
        });
    }

    getCardRole(card) {
        if (!card) return 'skill';
        if (card.role) return card.role;
        if (card.type === 'attack') return 'attack';
        if (card.type === 'defend') return 'defend';
        if (card.type === 'power') return 'power';
        return 'skill';
    }

    getCardRoleLabel(role) {
        const map = {
            attack: '攻击牌',
            defend: '防御牌',
            skill: '技能牌',
            power: '能力牌'
        };
        return map[role] || '技能牌';
    }

    formatCardCost(cost, mode = 'hand') {
        if (cost === undefined || cost === null) {
            return mode === 'hand' ? '—' : '耗能 —';
        }
        return mode === 'hand' ? cost : `耗能 ${cost}`;
    }

    renderCardContent(card, options = {}) {
        const role = this.getCardRole(card);
        const roleLabel = this.getCardRoleLabel(role);
        const mode = options.mode || 'hand';
        const costText = this.formatCardCost(card.cost, mode);
        const name = this.escapeHtml(card.name || '未知卡牌');
        const description = this.escapeHtml(card.description || '');
        const showUpgrade = options.showUpgrade !== false && card.upgraded;
        const upgradeMark = showUpgrade ? '<span class="card-upgrade-indicator">★</span>' : '';
        const typeBadgeClass = `card-type-badge card-type-${role}`;

        return `
            <div class="card-top">
                <span class="${typeBadgeClass}">${roleLabel}</span>
                <span class="card-cost">${costText}</span>
            </div>
            <div class="card-name">${name}${upgradeMark}</div>
            <div class="card-description">${description}</div>
        `;
    }

    applyCardAttribute(card, attribute, amount = 0) {
        if (!this.player || !attribute) return;
        const value = Number(amount) || 0;
        if (value === 0) return;

        switch (attribute) {
            case 'strength':
                this.player.addStrength(value, 'battle');
                break;
            case 'dexterity':
                this.player.addDexterity(value, 'battle');
                break;
            case 'intelligence':
                this.player.addIntelligence(value, 'battle');
                break;
            default:
                break;
        }
    }

    getDifficultyLabel(tier) {
        const labels = ['I', 'II', 'III', 'IV', 'V', 'VI'];
        return labels[Math.max(0, Math.min(labels.length - 1, (tier || 1) - 1))] || String(tier || 1);
    }

    loadDifficultyState() {
        try {
            const raw = localStorage.getItem('h5_uneven_difficulty');
            if (raw) {
                const data = JSON.parse(raw);
                if (typeof data.current === 'number') this.difficultyTier = data.current;
                if (typeof data.max === 'number') this.maxUnlockedTier = data.max;
            }
        } catch (e) {
            console.warn('读取难度信息失败', e);
        }
        this.difficultyTier = Math.min(6, Math.max(1, this.difficultyTier || 1));
        this.maxUnlockedTier = Math.min(6, Math.max(this.difficultyTier, this.maxUnlockedTier || 1));
    }

    saveDifficultyState() {
        try {
            localStorage.setItem('h5_uneven_difficulty', JSON.stringify({
                current: this.difficultyTier,
                max: this.maxUnlockedTier
            }));
        } catch (e) {
            console.warn('保存难度信息失败', e);
        }
    }

    updateDifficultyUI() {
        const currentLabel = this.getDifficultyLabel(this.difficultyTier);
        const maxLabel = this.getDifficultyLabel(this.maxUnlockedTier);
        const currentEl = document.getElementById('difficulty-current-label');
        if (currentEl) currentEl.textContent = currentLabel;
        const maxEl = document.getElementById('difficulty-max-label');
        if (maxEl) maxEl.textContent = maxLabel;
        const mapDiff = document.getElementById('map-difficulty-label');
        if (mapDiff) mapDiff.textContent = currentLabel;
        const battleDiff = document.getElementById('battle-difficulty-label');
        if (battleDiff) battleDiff.textContent = currentLabel;

        const difficultyPrev = document.getElementById('difficulty-prev');
        if (difficultyPrev) difficultyPrev.disabled = this.difficultyTier <= 1;
        const difficultyNext = document.getElementById('difficulty-next');
        if (difficultyNext) difficultyNext.disabled = this.difficultyTier >= this.maxUnlockedTier;
    }

    changeDifficulty(delta) {
        if (!delta) return;
        const target = Math.min(this.maxUnlockedTier, Math.max(1, this.difficultyTier + delta));
        if (target === this.difficultyTier) return;
        this.difficultyTier = target;
        this.saveDifficultyState();
        this.updateDifficultyUI();
    }

    advanceDifficultyAfterVictory() {
        const nextTier = Math.min(6, this.difficultyTier + 1);
        if (nextTier > this.maxUnlockedTier) {
            this.returnToMainMenu();
            return;
        }
        this.difficultyTier = nextTier;
        this.saveDifficultyState();
        this.updateDifficultyUI();
        this.returnToMainMenu();
    }

    unlockNextDifficulty() {
        if (this.difficultyTier < 6 && this.maxUnlockedTier < this.difficultyTier + 1) {
            this.maxUnlockedTier = this.difficultyTier + 1;
            this.saveDifficultyState();
            this.updateDifficultyUI();
        } else {
            this.saveDifficultyState();
        }
    }

    returnToMainMenu() {
        this.restartGame();
        this.updateDifficultyUI();
    }

    triggerHeavenlyBlessing() {
        if (this.eventManager) {
            this.eventManager.triggerHeavenlyBlessing();
        }
    }

    legacyPreloadAvatarFrames() {
        return;
    }

    showScreen(screenId) {
        document.querySelectorAll('.screen').forEach(screen => {
            screen.classList.remove('active');
        });
        const targetScreen = document.getElementById(screenId);
        if (targetScreen) {
            targetScreen.classList.add('active');
            this.currentScreen = screenId;
        } else {
            console.error(`Screen ${screenId} not found`);
        }
    }

    updateUI() {
        if (this.player) {
            const healthEl = document.getElementById('player-health');
            const energyEl = document.getElementById('player-energy');
            if (healthEl) healthEl.textContent = this.player.health;
            if (energyEl) energyEl.textContent = this.player.energy;
            const goldEl = document.getElementById('player-gold');
            if (goldEl) goldEl.textContent = this.playerGold;
            const floorEl = document.getElementById('current-floor');
            if (floorEl) floorEl.textContent = this.currentFloor;
            this.updatePotionsDisplay();
            this.updateRelicsDisplay();
            this.updatePlayerAvatar();
        }
        const battleDiff = document.getElementById('battle-difficulty-label');
        if (battleDiff) {
            battleDiff.textContent = this.getDifficultyLabel(this.difficultyTier);
        }
    }

    updatePotionsDisplay() {
        const potionsContainer = document.getElementById('potions-display');
        if (!potionsContainer) return;

        potionsContainer.innerHTML = '';

        if (!this.playerPotions || this.playerPotions.length === 0) {
            potionsContainer.innerHTML = '<span style="color: #999; font-style: italic;">无</span>';
            return;
        }

        this.playerPotions.forEach((potion, index) => {
            const potionIcon = document.createElement('span');
            potionIcon.className = 'potion-icon';
            potionIcon.textContent = potion.name;
            potionIcon.title = potion.description || potion.name;
            potionIcon.addEventListener('click', () => {
                this.usePotion(index);
            });
            potionsContainer.appendChild(potionIcon);
        });
    }

    updateRelicsDisplay() {
        const relicsContainer = document.getElementById('relics-display');
        const relicsDisplayFull = document.getElementById('relics-display-full');

        if (relicsContainer) {
            relicsContainer.innerHTML = '';
            if (!this.playerRelics || this.playerRelics.length === 0) {
                relicsContainer.innerHTML = '<span style="color: #999; font-style: italic;">无</span>';
            } else {
                const displayCount = Math.min(3, this.playerRelics.length);
                for (let i = 0; i < displayCount; i++) {
                    const relic = this.playerRelics[i];
                    const relicIcon = document.createElement('span');
                    relicIcon.className = `relic-icon rarity-${relic.rarity || 'common'}`;
                    relicIcon.textContent = relic.name;
                    relicIcon.title = `${relic.name}: ${relic.description}`;
                    relicsContainer.appendChild(relicIcon);
                }
                if (this.playerRelics.length > 3) {
                    const moreText = document.createElement('span');
                    moreText.className = 'relic-more';
                    moreText.textContent = `+${this.playerRelics.length - 3}`;
                    moreText.title = `还有${this.playerRelics.length - 3}件遗物`;
                    relicsContainer.appendChild(moreText);
                }
            }
        }

        if (relicsDisplayFull) {
            relicsDisplayFull.innerHTML = '';
            if (!this.playerRelics || this.playerRelics.length === 0) {
                relicsDisplayFull.innerHTML = '<span style="color: #999; font-style: italic;">暂无遗物</span>';
            } else {
                this.playerRelics.forEach(relic => {
                    const relicIcon = document.createElement('span');
                    relicIcon.className = `relic-icon rarity-${relic.rarity || 'common'}`;
                    relicIcon.textContent = relic.name;
                    relicIcon.title = `${relic.name}: ${relic.description}`;
                    relicsDisplayFull.appendChild(relicIcon);
                });
            }
        }
    }

    updateHandDisplay() {
        const handContainer = document.getElementById('player-hand');
        if (!handContainer) {
            console.error('Hand container not found');
            return;
        }

        handContainer.innerHTML = '';

        this.playerHand.forEach((card, index) => {
            const cardElement = document.createElement('div');
            cardElement.className = 'card';
            cardElement.setAttribute('data-card-index', index);

            const rarity = card.rarity || 'common';
            cardElement.classList.add(`rarity-${rarity}`);
            const role = this.getCardRole(card);
            cardElement.classList.add(`card-role-${role}`);

            cardElement.innerHTML = this.renderCardContent(card, { mode: 'hand' });
            cardElement.addEventListener('click', () => {
                if (this.player && this.player.energy < card.cost) {
                    this.showEnergyInsufficientWarning(card);
                    return;
                }
                this.playSound('card');
                this.animateCardUse(cardElement);
                setTimeout(() => {
                    this.useCard(card);
                }, 200);
            });

            cardElement.addEventListener('mouseenter', () => {
                cardElement.classList.add('card-hover');
            });
            cardElement.addEventListener('mouseleave', () => {
                cardElement.classList.remove('card-hover');
            });
            handContainer.appendChild(cardElement);
        });
    }

    updateBattleDisplay() {
        if (this.battleManager) {
            return this.battleManager.updateBattleDisplay();
        }
    }

    addBattleLog(message) {
        this.battleLog = this.battleLog || [];
        this.battleLog.push(message);
        this.updateBattleLogDisplay();
    }

    updateBattleLogDisplay() {
        const logContainer = document.getElementById('battle-log-content');
        if (!logContainer) return;

        logContainer.innerHTML = '';

        const recentLogs = (this.battleLog || []).slice(-20);
        recentLogs.forEach(log => {
            const logElement = document.createElement('div');
            logElement.className = 'log-entry';
            if (typeof log === 'string') {
                if (log.includes('对玩家造成了') || log.includes('攻击')) {
                    logElement.classList.add('enemy-action');
                } else if (log.includes('使用卡牌') || log.includes('获得') || log.includes('造成')) {
                    logElement.classList.add('player-action');
                } else if (log.includes('回合开始') || log.includes('回合结束')) {
                    logElement.classList.add('turn-start');
                } else {
                    logElement.classList.add('system');
                }
                logElement.textContent = log;
            } else {
                logElement.textContent = String(log);
            }
            logContainer.appendChild(logElement);
        });

        logContainer.scrollTop = logContainer.scrollHeight;
    }
}